package com.pan.server.impl;

import com.pan.entity.HumbleHttpRequest;
import com.pan.hendle.resp.ResponseHandle;
import com.pan.hendle.resp.config.DefaultHtmlRead;

import java.io.*;
import java.net.Socket;

public class HumbleHttpSingleServer
        extends BasicServer implements DefaultHtmlRead {



    @Override
    public void run() {
        while (true) {
            Socket acceptSocket = null;
            try {
                acceptSocket = super.getServerSocket().accept();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            while (true) {
                HumbleHttpRequest httpReq = (HumbleHttpRequest) super.getRequestHandle().receive(acceptSocket);
                if (httpReq == null) {
                    try {
                        acceptSocket.shutdownInput();
                        acceptSocket.shutdownOutput();
                        acceptSocket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    break;//end this connection
                }
                //todo: 因该要有一个储存MyHumbleServlet容器，根据HttpReq的url转发给对应的MyHumbleServlet，MyHumbleServlet处理后，返回HttpResp
                System.out.println(httpReq.toString());
                OutputStream outputStream = null;
                ResponseHandle responseHandle = getResponseHandle();
                String response = responseHandle.back(httpReq);
                try {
                    outputStream = acceptSocket.getOutputStream();
                    PrintWriter printWriter = new PrintWriter(outputStream,true);
                    printWriter.print(response);
                    printWriter.flush();
                    acceptSocket.shutdownOutput();
                    acceptSocket.close();
                    break;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }

        }
    }
}
